package pl.com.sthaether.mc;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.Dialogs;
import pl.com.sthaether.mc.config.MCMainConfiguration;
import pl.com.sthaether.mc.main.MCMainPane;

import java.io.File;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/*
 * TODO sections - order by priority
 * 
 * 	-important:
 *  #error - something really bad
 *  #problem - something not working proper
 *  #needToDo - something that must be done
 * 	#toAnalyse - something that potentially could be done, but it's not sure
 *  
 * 	-normal:
 *  #toTests - something that needs to be tested
 *  #performance - something that works really bad
 * 	#visuals - something ugly to fix
 *  #goodToDo - something unnecessary but could be done
 *  
 * 	-optional:
 *  #userFrendly - something that should be done better and easier for user
 * 	#optionalToDo - something nice but don't needed
 * 
 * 	-out of priority:
 * 	#waitForMore - need more code to do anything more
 * 	#analyseWhenMore - need to analyse but at current state it can't be done
 * 
 * 
 * 
 */
public class MCApplication extends Application {

    private static Logger logger;

    private static Stage primaryStage;
    private static Scene primaryScene;

    public static void main(String[] args) {
        launch(args);
    }

    private static void initWindowBehaviorHandling() {
        primaryStage.setOnCloseRequest((event) -> {
            event.consume();
            showExitActionConfirm();
        });


    }

    private static void initSystemLogger() {
        logger = Logger.getLogger("MainLogger");
        logger.info("Logger Fine!");
        try {
            String filePath = System.getProperty("user.home") + "/[MC]Mapper/logs/LogFile" + new Date().toString() + ".log";
            final File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            } else {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileHandler fh;
            fh = new FileHandler(filePath);
            logger.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            logger.info("Logger file Fine");
        } catch (Exception e) {
            logger.throwing("Logger file Fail", "initSystemLogger", e);
        }


    }

    private static void initScene() {
        primaryScene = new Scene(MCMainPane.getInstance(), MCMainConfiguration.getApplicationWidth(), MCMainConfiguration.getApplicationHeight());
        primaryStage.setScene(primaryScene);
    }

    public static Stage getPrimaryStage() {
        return primaryStage;
    }

    public static void showExitActionConfirm() {
        Action response = Dialogs.create().owner(MCApplication.getPrimaryStage()).title("Exit Mapper").message("Are you sure you want to exit?\nAny unsaved changes will be lost.")
                .actions(Dialog.Actions.OK, Dialog.Actions.CANCEL).showConfirm();
        if (response == Dialog.Actions.OK) {
            logger.info("Exit confirmed");
            // TODO do something that should be done before exit
            System.exit(0);
        }
    }

    public static void logInfo(String info) {
        logger.info(info);
    }

    public static void logWarn(String warn) {
        logger.warning(warn);
    }

    public static void logException(String info, Throwable exc) {
        logger.throwing(info, "", exc);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        MCApplication.primaryStage = primaryStage;
        primaryStage.setTitle("[MC]Mapper");
        initSystemLogger();
        MCMainConfiguration.initConfiguration();
        initWindowBehaviorHandling();
        initScene();
        primaryStage.show();
    }

}
